//
//  ElectricalCertificateViewController.swift
//  ezyform
//
//  Created by MoennigQ on 11/9/20.
//  Copyright © 2020 Client.Solution Pty Ltd. All rights reserved.
//
import UIKit
import WebKit
import HandyJSON
import MBProgressHUD
class ElectricalCertificateViewController: BaseViewController {
    let customView = ElectricalCertificateView()
    //从customView单独抽取Pickerview，防止pickerview失效，因为customView中hitTest拦截了滑动手势
    lazy var pickerView: ElectricalDatePickerview = {
        return ElectricalDatePickerview()
    }()
    let webViewExport = WKWebView()
    let webView = WKWebView()
    let backView = UIView()
    var escModel = ESCInfoModel()
    
    let semphore = DispatchSemaphore(value: 0)
    var viewTopMargin: CGFloat = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initUI()
    }
    
    func initUI(){
        self.view = self.customView
        self.customView.setTitleInfo(R.string.localizable.electricalSafetyCertificate())
        //预览
        self.customView.previewBtn.addTarget(self, action: #selector(previewBtnClick), for: UIControl.Event.touchUpInside)
        //
        customView.backToPreBtn.addTarget(self, action: #selector(backToPre), for: UIControl.Event.touchUpInside)
        customView.cancelBtn.addTarget(self, action: #selector(backToPre), for: UIControl.Event.touchUpInside)
        customView.addBtn.addTarget(self, action: #selector(addBtnClick), for: UIControl.Event.touchUpInside)
        //show date picker view
        customView.dateCalendarBtn.addTarget(self, action: #selector(showDatePicker(_:)), for: UIControl.Event.touchUpInside)
        customView.dateOfTestCalendarBtn.addTarget(self, action: #selector(showDatePicker(_:)), for: UIControl.Event.touchUpInside)
     
        //init data
        self.customView.setData(JobDetailModelHelper.shared.jobDetailModel)
        self.loadData()
    }
    func loadData(){
        InstallationDetailVCHelper.shared.cacheJobDetail(R.string.localizable.loading()) {
            self.customView.setData(JobDetailModelHelper.shared.jobDetailModel)
        } faildClosure: { code, error in
            Tool().showErrorInfo(code,error)
        }
    }
    
    @objc func showDatePicker(_ sender: UIButton){
        self.customView.endEditing(true)
        if self.pickerView.superview == nil {
            self.navigationController?.view.addSubview(pickerView)
            pickerView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            self.pickerView.setPickerDefaultData()
            self.pickerView.datePicker.selectRow(1, inComponent: 2, animated: true)
            self.pickerView.datePicker.reloadComponent(1)
            self.pickerView.datePicker.selectRow(self.pickerView.currentMonth - 1, inComponent: 1, animated: true)
            self.pickerView.datePicker.reloadComponent(0)
            self.pickerView.datePicker.selectRow(self.pickerView.currentDay - 1, inComponent: 0, animated: true)
            
            self.pickerView.isHidden = false
            self.pickerView.doneClosure = { [weak self](dateStr) in
                guard let strongSelf = self else {return}
                if dateStr != "" {
                    if sender.tag == 1{
                        strongSelf.customView.dateOfTestTextfield.textField.text = dateStr
                    }else if sender.tag == 2{
                        strongSelf.customView.signDateTextfield.textField.text = dateStr
                    }
                }
                strongSelf.pickerView.removeFromSuperview()
            }
        }
        
    }

    @objc override  func backToPre() {
        self.escModel = self.customView.getAllFieldData()
        DBManager.shared.saveESCInfo(self.escModel)
        self.navigationController?.popViewController(animated: false)
    }
    
    @objc func closeBtnClick(){
        if let _ = self.backView.superview {
            self.backView.removeFromSuperview()
        }
    }
    @objc func addBtnClick(){
        self.escModel = self.customView.getAllFieldData()
        webViewExport.frame = CGRect(x: 0, y: 0, width: APPConfig.A4PaperSize.width, height: APPConfig.A4PaperSize.height)
        webViewExport.isHidden = true
        self.customView.addSubview(webViewExport)
        self.webViewExport.navigationDelegate = self
        //加载本地test.html文件
        guard let url = Bundle.main.url(forResource: "ESC", withExtension: "html") else {
            return
        }
        //add Loading view
        ModelViewUtil.shared.showLoadingView("Adding ESC...")
        webViewExport.loadFileURL(url, allowingReadAccessTo: Bundle.main.bundleURL)
        //延时save image
        let delay = Double(3) * Double(NSEC_PER_SEC)
        let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
        DispatchQueue.main.asyncAfter(deadline: time) {
            let image = self.webViewExport.exportHTMLToImage()
            if let _ = self.webViewExport.superview{
                self.webViewExport.removeFromSuperview()
            }
            
            ModelViewUtil.shared.hideLoadingView()
            self.savePhoto(originImage: image)
            //增加完ESC，返回到image list
            self.navigationController?.popViewController(animated: false)
        }
    }
    @objc func previewBtnClick(){
        //获取所有字段信息
        self.escModel = self.customView.getAllFieldData()
        backView.backgroundColor = UIColor.black.withAlphaComponent(0.8)
        self.navigationController?.view.addSubview(backView)
        backView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(closeBtnClick))
        backView.addGestureRecognizer(tapGesture)
        //
        var navigationBarHeight: CGFloat = 50
        if APPConfig.WidthForPortrait >= 320 {
            navigationBarHeight = 80
        }
        
        webView.navigationDelegate = self
        //加载本地test.html文件
        guard let url = Bundle.main.url(forResource: "ESC", withExtension: "html") else {
            return
        }
        webView.loadFileURL(url, allowingReadAccessTo: Bundle.main.bundleURL)
        
        let maxHeight: CGFloat = APPConfig.HeightForPortrait - navigationBarHeight * 2
        let webViewBackView = UIView()
        webViewBackView.backgroundColor = .white
        backView.addSubview(webViewBackView)
        webViewBackView.snp.makeConstraints { (make) in
            make.centerY.left.right.equalToSuperview()
            make.height.equalTo(maxHeight)
        }
        webViewBackView.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20))
        }
        let closeBtn = UIButton()
        closeBtn.setImage(UIImage(named: "installation_detail_checklist_esc_close_icon"), for: UIControl.State.normal)
        closeBtn.clipsToBounds = true
        backView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { (make) in
            make.top.equalTo(webViewBackView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(navigationBarHeight)
        }
        closeBtn.addTarget(self, action: #selector(closeBtnClick), for: UIControl.Event.touchUpInside)
    }
    func savePhoto(originImage: UIImage){
        let originImageData = originImage.jpegData(compressionQuality: 1.0)! as NSData
        
        let fileName = DateUtil().getCurrentDatetimeTamp()
        //checklist image
        let imagePath = FileUtil().getChecklistImagePath(fileName)
        
        do {
            try originImageData.write(to: URL(fileURLWithPath: imagePath), options: [.atomic])
            
            let dbModel = CheckListImageDBModel()
            dbModel.checklist_id = JobDetailModelHelper.shared.checklistModel.id
            dbModel.pvd_id = JobDetailModelHelper.shared.jobDetailModel.id
            dbModel.id = fileName
            dbModel.image = imagePath
            
            dbModel.record_at = DateUtil().getCurrentDatetime()
            dbModel.title = JobDetailModelHelper.shared.checklistModel.title
            dbModel.oper_type = DataOperType.Add.rawValue
            
            //0.必须先插入数据库，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.insertChecklistImages(model: dbModel)
            //1.增加到当前list中
            JobDetailModelHelper.shared.checklistModel.images.insert(dbModel, at: 0)
            if let index = JobDetailModelHelper.shared.jobDetailModel.pvd_checklists.firstIndex(where: {$0.id == JobDetailModelHelper.shared.checklistModel.id}){
                JobDetailModelHelper.shared.jobDetailModel.pvd_checklists[index] = JobDetailModelHelper.shared.checklistModel
                JobDetailModelHelper.shared.jobDetailModel.broadCastChecklistData()
            }
            //2.上传
            UploadManager.shared.uploadChecklistImage(imageModel: dbModel)
        }catch{
            NSLog("Saving checklist image to local failed")
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
extension ElectricalCertificateViewController:  WKNavigationDelegate{
    //WKNavigationDelegate
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print(error)
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if !webView.isLoading {
            webView.evaluateJavaScript("document.readyState") { (readState, err) in
                if let data = readState as? String,data == "complete" {
                    self.fillDataInHtml(webView)
                }
            }
        }
    }
    func fillDataInHtml(_ webView: WKWebView){
        var js: String = ""
        //installation checkbox
        if let data = self.escModel.installation_flag, data {
            js = js +  String.localizedStringWithFormat("document.getElementById('checkbox1').checked = true;", data)
        }
        //equipment checkbox
        if let data = self.escModel.equipment_flag, data {
            js = js +  String.localizedStringWithFormat("document.getElementById('checkbox2').checked = true;", data)
        }
        //owner name title
        if let data = self.escModel.owner_name_title {
            js = js +  String.localizedStringWithFormat("document.getElementById('work_performed_title').innerText = '%@';", data)
        }
        //owner given name
        if let data = self.escModel.owner_given_name {
            js = js +  String.localizedStringWithFormat("document.getElementById('work_performed_first_name').innerText = '%@';", data)
        }
        //owner surname
        if let data = self.escModel.owner_surname {
            js = js +  String.localizedStringWithFormat("document.getElementById('work_performed_last_name').innerText = '%@';", data)
        }
        //address street
        if let data = self.escModel.installation_address_street_name {
            js = js +  String.localizedStringWithFormat("document.getElementById('address_street').innerText = '%@';", data)
        }
        //address suburb
        if let data = self.escModel.installation_address_suburb {
            js = js +  String.localizedStringWithFormat("document.getElementById('address_suburb').innerText = '%@';", data)
        }
        //address postcode
        if let data = self.escModel.installation_address_postcode {
            js = js +  String.localizedStringWithFormat("document.getElementById('address_postcode').innerText = '%@';", data)
        }
        //tested description
        if let data = self.escModel.installation_equipment_tested_descrip {
            let resultStr = (data as NSString).replacingOccurrences(of: "\n", with: "<br/>")
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_info').innerHTML = '%@';", resultStr)
        }
        //date of test
        if let data = self.escModel.date_of_test {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_date').innerText = '%@';", data)
        }
        //contractor license number
        if let data = self.escModel.contractor_licence_number {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_licence').innerText = '%@';", data)
        }
        //contractor license name
        if let data = self.escModel.contractor_licence_name {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_name_licence').innerText = '%@';", data)
        }
        //contractor license phone
        if let data = self.escModel.contractor_licence_phone {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_phone_number').innerText = '%@';", data)
        }
        //electrician name
        if let data = self.escModel.electrician_name {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_name').innerText = '%@';", data)
        }
        //sign date
        if let data = self.escModel.sign_date {
            js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_signature_date').innerText = '%@';", data)
        }
        //signature image
        js = js +  String.localizedStringWithFormat("document.getElementById('electrical_installation_signature_img').src = \"%@\"", self.getSignature())
        
        if js != "" {
            webView.evaluateJavaScript(js,completionHandler: nil) 
        }
        if webView == self.webViewExport{
            self.webViewExport.evaluateJavaScript("document.documentElement.scrollHeight") { (result, err) in
                if let height = result as? CGFloat {
//                    print("scrollHeight: \(height)")
                    self.webViewExport.frame = CGRect(x: 0, y: 0, width: APPConfig.A4PaperSize.width, height: height)
                }
            }
        }
        
    }
    private func getSignature()->String{
        let image = self.customView.signatureView.getSignature()
        var imageSource: String = ""
        if let imageData = image.pngData(){
            imageSource = String(format: "data:image/png;base64,%@",imageData.base64EncodedString(options: Data.Base64EncodingOptions.endLineWithCarriageReturn))
        }
        return imageSource
    }
}
